home *** CD-ROM | disk | FTP | other *** search
- Path: news.pge.com!usenet
- From: psk3@pge.com (Phillip Knight)
- Newsgroups: comp.lang.c++
- Subject: Re: A curly one for gurus: possible to create a value array of derived objects?
- Date: 15 Feb 1996 19:00:34 GMT
- Organization: Pacific Gas and Electric
- Distribution: world
- Message-ID: <4fvvsi$kk8@news02.comp.pge.com>
- References: <4fuho2$d3s@mblisd.macqbl.com.au>
- NNTP-Posting-Host: psk3ws04.comp.pge.com
- Mime-Version: 1.0
- Content-Type: Text/Plain; charset=US-ASCII
- X-Newsreader: WinVN 0.99.6
-
- In article <4fuho2$d3s@mblisd.macqbl.com.au>, steven@macquarie.com.au says...
- >
- >
- >Ok This is a real curly question:
- >
- >Is it possible to create (and manage) a "value" array of objects from
- >derived classes?
- >
- >E.g:
- >
- >struct A { virtual char* name() { return "A"; } };
- >struct B : public A { int data1; virtual char* name() { return "B"; } };
- >struct C : public A { double data2; virtual char* name() { return "C"; } };
- >
- >To be able to provide access to an array of B's and C's without occuring
- >the overhead of pointer indirection, I am hoping it is somehow possible to
- >have something like:
- >
- >#include <stdio.h>
- >main()
- >{
- > A* a = new A[10];
- > B b;
- > C c;
- >
- > a[0] = b;
- > a[1] = c;
- >
- > printf("%s\n", a[0].name());
- > printf("%s\n", a[1].name());
- >}
- >
- >
- >The output from this (as you may have already guessed) is
- >A
- >A
- >
- >and not
- >B
- >C
- >
- >The problem here is I guess "data slicing" and the use of the default
- operator=.
- >Is it possible to somehow get over this
- >by faking a union? I can't use unions in practice because my derived classes
- >have (default) constructors.
- >
- >The idea for this came from the "Composite" pattern in the Design Patterns
- >book by Gamma/Helm/Johnson/Vlissides. The "A" class above being the
- "Composite"
- >object, and the "B" and "C" being the "Component" objects.
- >
- >Thanks for any solutions/suggestions you can provide.
- >Steve
- >---
- >
- >////////////////////////////////////////////////////////////////////////////
- >// Steven James Brown Disclaimer: Any comments or //
- >// Qantitative Applications views made are my own and are //
- >// Macquarie Bank Limited unrelated to those of my //
- >// steven@macquarie.com.au employer. //
- >// //
- >////////////////////////////////////////////////////////////////////////////
- >
- >
- >
- steven, does class A have an A(B&) copy constructor? you created an array
- of A, and copying a A derived class will get you the A copy constructor. this
- is of course for data -- forget the virtual functions, because you really only
- have a class A. as a latter post points out, using a lval array is the way
- to get to those virtual functions.
-
- good luck,
- phil
-
-